import {router, useRouter} from "expo-router";
import {useCallback} from "react";
import AlertService from "@/components/Global/Alert/service";
import {UserProfileType} from "@/types/user-profile";
import {useChatSessionActions} from "@/hooks/chat/chat-session";
import {SessionType} from "@/types/chat-session";
import {useWebRTCCall} from "@/hooks/webrtc/user-call";
import {useUserProfileState} from "@/hooks/user/user-profile";
import {ChatUser} from "@/types/chat-message";
import {useChatUserActions} from "@/hooks/chat/chat-user";
import {useChatMessageActions} from "@/hooks/chat/chat-message";

/**
 * 好友通信相关的 hook
 * 处理与好友的消息、语音通话和视频通话功能
 */
export const useFriendCommunication = () => {
    const router = useRouter();
    // 引入会话相关的actions
    const {addSession, getSessionById} = useChatSessionActions();
    const {upsertProfile} = useChatUserActions();
    const {currentUser} = useUserProfileState();
    const chatUser: ChatUser = {
        avatar: currentUser.avatar,
        id: currentUser.id,
        name: currentUser.nickname,
        updateTime: currentUser.updateTime,
    }
    const {callUser} = useWebRTCCall(chatUser)
    const {setCurrentChatDetailState} = useChatMessageActions()

    /**
     * 发送消息给好友
     * @param friend 好友信息
     */
    const handleSendMessage = useCallback(
        async (friend: UserProfileType) => {
            try {
                // 更新用户信息
                await upsertProfile({
                    id: friend.id,
                    name: friend.nickname,
                    avatar: friend.avatar,
                    updateTime: friend.updateTime
                })

                let session = await getSessionById(friend.id)
                if (!session) {
                    // 先创建或确保会话存在
                    await addSession({
                        sessionId: friend.id,
                        sessionType: SessionType.SINGLE,
                    });
                    session = await getSessionById(friend.id)
                }
                setCurrentChatDetailState(session);
                router.navigate("chat/chat-detail");
            } catch (error) {
                console.error("Error navigating to chat:", error);
                AlertService.showAlert("error", "无法打开聊天页面");
            }
        },
        [router, addSession]
    );

    /**
     * 发起视频通话
     * @param friend 好友信息
     */
    const handleVideoCall = useCallback(
        async (friend: UserProfileType) => {
            try {
                // 发起offer
                await callUser(friend.id);
                // 导航到视频通话页面
                router.navigate({
                    pathname: "/call/video-realtime-call",
                    params: {
                        id: friend.id,
                        name: friend.nickname,
                        avatar: friend.avatar,
                    },
                });
            } catch (error) {
                console.error("Error starting video call:", error);
                AlertService.showAlert("error", "无法发起视频通话");
            }
        },
        [router]
    );

    /**
     * 发起语音通话
     * @param friend 好友信息
     */
    const handleVoiceCall = useCallback(
        (friend: UserProfileType) => {
            try {
                // 这里可以实现语音通话的逻辑
                // 例如：调用语音通话 API、导航到语音通话页面等
                console.log("Starting voice call with:", friend.nickname);

                // 示例：导航到语音通话页面
                router.push({
                    pathname: "/call/voice-realtime-call",
                    params: {
                        friendId: friend.id,
                        friendName: friend.nickname,
                        friendAvatar: friend.avatar,
                    },
                });
            } catch (error) {
                console.error("Error starting voice call:", error);
                AlertService.showAlert("error", "无法发起语音通话");
            }
        },
        [router]
    );

    return {
        handleSendMessage,
        handleVideoCall,
        handleVoiceCall,
    };
};
